﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

namespace JESAI.Common.Util.线程.代码锁.业务代码锁套装.Default
{
    /// <summary>
    /// 业务锁
    /// </summary>
    public class DefaultLock : ILock
    {
        /// <summary>
        /// 缓存
        /// </summary>
        private static ConcurrentDictionary<string,object> dict=new ConcurrentDictionary<string, object>();
        /// <summary>
        /// 锁定标识
        /// </summary>
        private string _key;
        /// <summary>
        /// 延迟执行时间
        /// </summary>
        private TimeSpan? _expiration;

        /// <summary>
        /// 初始化业务锁
        /// </summary>
        /// <param name="cache">缓存</param>
        public DefaultLock()
        {
            
        }

        /// <summary>
        /// 锁定，成功锁定返回true，false代表之前已被锁定
        /// </summary>
        /// <param name="key">锁定标识</param>
        /// <param name="expiration">锁定时间间隔</param>
        public bool Lock(string key, TimeSpan? expiration = null)
        {
            _key = key;
            _expiration = expiration;
            if (dict.ContainsKey(key))
                return false;
            return dict.TryAdd(key, expiration);
        }

        /// <summary>
        /// 解除锁定
        /// </summary>
        public void UnLock()
        {
            if (_expiration != null)
                return;
            if (dict.ContainsKey(_key) == false)
                return;
            dict.TryRemove(_key,out object data);
        }
    }
}
